/**  防抖(debounce) */
function debounce(
  fn: Function,
  delay: number = 300,
  before: boolean = true
): Function {
  if (!fn) return function () {}

  let timer: number | null = null

  return function (...opt: any[]) {
    if (timer) {
      clearTimeout(timer)
    } else if (before) {
      fn(...opt)
    }

    timer = setTimeout(() => {
      timer = null

      if (before) return
      fn(...opt)
    }, delay)
  }
}

/** 节流(throttle)
 *
 * befor 前调用还是后调
 */
function throttle(
  fn: Function,
  delay: number = 500,
  before: boolean = true
): Function {
  if (!fn) return function () {}

  let valid = true

  return function (...opt: any[]) {
    if (!valid) {
      //休息时间 暂不接客
      return false
    }
    // 工作时间，执行函数并且在间隔期内把状态位设为无效
    valid = false
    // 节流前调用
    // | ... | ...
    if (before) {
      fn(...opt)
    }
    setTimeout(() => {
      valid = true
      // 节流后 调用
      // ... | ... |
      if (before) return
      fn(...opt)
    }, delay)
  }
}

export { debounce, throttle }
